package upmc.fr.android.rss.parser;

import java.text.ParseException;
import java.util.Calendar;

import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;

import upmc.fr.android.model.RSSArticle;
import upmc.fr.android.model.RSSFlow;



/**
 * Parsing du XML provenant d'un flux 
 */
public class RSSHandler extends DefaultHandler
{
	private static RSSHandler instance;	
	private DateParser parser;
	private boolean inChannel;
	private boolean inItem;
	private boolean inTitle;
	private boolean inLink;
	private boolean inDescription;
	private boolean inPubDate;
	
	//a la fin de chaque parsing, le result doit etre mis a jour
	private RSSFlow result;
	private RSSArticle article;
	
	private RSSHandler()
	{		
		parser = new DateParser();
	}
	
	public static RSSHandler getInstance()
	{
		if(instance == null)
			instance = new RSSHandler();
		return instance;
	}
	
	@Override
	public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException 
	{
		if("channel".equals(qName))
		{			
			result = new RSSFlow();
			inChannel = true;
		}
		
		if("item".equals(qName))
		{			
			article = new RSSArticle();
			inItem = true;
		}		
		
		if("title".equals(qName))
			inTitle = true;	
		if("description".equals(qName))
			inDescription = true;		
		if("link".equals(qName))
			inLink = true;	
		if("pubDate".equals(qName))
			inPubDate = true;		
	}
	
	@Override
	public void endElement(String uri, String localName, String qName) throws SAXException 
	{				
		if("channel".equals(qName))
			inChannel = false;	
		
		if("item".equals(qName))
		{		
			result.addArticle(article);
			inItem = false;			
		}		
		if("title".equals(qName))
			inTitle = false;		
		if("description".equals(qName))
			inDescription = false;			
		if("link".equals(qName))
			inLink = false;			
		if("pubDate".equals(qName))
			inPubDate = false;			
	}
	
	@Override
	public void characters(char[] ch, int start, int length) throws SAXException 
	{
		String value = new String(ch, start, length);		
				
		if(inItem)
		{
			if(inTitle)
				article.setTitle(value);
			if(inDescription)
				article.setDescription(value);
			if(inLink)
				article.setUrl(value);
			if(inPubDate)
			{
				try 
				{
					article.setDate(parser.parse(value));
				}
				catch (ParseException e) 
				{			
					article.setDate(Calendar.getInstance().getTime());
				} 
			}
		}
		else if(inChannel)
		{
			if(inTitle)
				result.setTitle(value);
			if(inDescription)
				result.setDescription(value);
			if(inLink)
				result.setUrl(value);			
		}		
	}
	
	public RSSFlow getResult()
	{
		return result;
	}
}
